package com.example.daxiguaforharmony.manager;

import com.example.daxiguaforharmony.ui.DeviceSelectDialog;
import com.example.daxiguaforharmony.utils.DeviceUtils;
import com.example.daxiguaforharmony.utils.LogUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.ability.IAbilityContinuation;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import com.example.daxiguaforharmony.manager.CrossDevicePlayerInterfaceProxy;
import ohos.bundle.ElementName;
//import ohos.data.distributed.device.DeviceInfo;
import ohos.distributedschedule.interwork.DeviceInfo;
import ohos.distributedschedule.interwork.DeviceManager;
import ohos.rpc.IRemoteObject;

import java.util.List;

public class CrossDeviceManager implements IAbilityContinuation {
    private static CrossDeviceManager _instance = null;
    public static CrossDeviceManager getInstance() {
        if (_instance == null) {
            synchronized (CrossDeviceManager.class) {
                if (_instance == null) _instance = new CrossDeviceManager();
            }
        }
        return _instance;
    }

    private static final String TAG = CrossDeviceManager.class.getSimpleName();

    //连接本地服务
    CrossDevicePlayerInterfaceProxy localPlayerInterfaceProxy = null;
    //连接远程服务
    CrossDevicePlayerInterfaceProxy remotePlayerInterfaceProxy = null;

    private IAbilityConnection localAbilityConnection = null;
    private IAbilityConnection remoteAbilityConnection = null;
    private AbilitySlice abilitySlice = null;
    private boolean emptyDevice = false;
    private Operation localOperation;
    private Operation remoteOperation;
    private Operation remoteMainOperation;
    private Intent localIntent;
    private Intent remoteIntent;
    private Intent remoteMainIntent;

    public CrossDeviceManager() {
        this.localAbilityConnection = new IAbilityConnection() {
            @Override
            public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int i) {
                localPlayerInterfaceProxy = new CrossDevicePlayerInterfaceProxy(iRemoteObject);
            }

            @Override
            public void onAbilityDisconnectDone(ElementName elementName, int i) {
                localPlayerInterfaceProxy = null;
            }
        };

        this.remoteAbilityConnection = new IAbilityConnection() {
            @Override
            public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int i) {
                System.out.println("Game远程连接上了======");
                remotePlayerInterfaceProxy = new CrossDevicePlayerInterfaceProxy(iRemoteObject);
            }

            @Override
            public void onAbilityDisconnectDone(ElementName elementName, int i) {
                System.out.println("Game远程断开了======");
                remotePlayerInterfaceProxy = null;
            }
        };
    }

    public void init(AbilitySlice abilitySlice) {
        this.abilitySlice = abilitySlice;
        DeviceInfo deviceInfo = new DeviceInfo();
        emptyDevice = DeviceUtils.getRemoteDevice().isEmpty();
        localOperation = new Intent.OperationBuilder()
                .withDeviceId(deviceInfo.getDeviceId())
                .withBundleName("com.example.daxiguaforharmony")
                .withAbilityName("com.example.daxiguaforharmony.MainAbility")
                .withFlags(Intent.FLAG_START_FOREGROUND_ABILITY)
                .build();
        localIntent = new Intent();
        localIntent.setOperation(localOperation);

        try {
            this.abilitySlice.connectAbility(localIntent, localAbilityConnection);
        }catch (Exception e) {
            e.printStackTrace();
        }

        if(!emptyDevice) {
//            remoteOperation = new Intent.OperationBuilder()
//                    .withDeviceId(DeviceUtils.getRemoteDevice().get(0).getDeviceId())
//                    .withBundleName("com.example.daxiguaforharmony")
//                    .withAbilityName("com.example.daxiguaforharmony.MainAbility")
//                    .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
//                    .build();
//
//
//            remoteIntent = new Intent();
//            remoteIntent.setOperation(remoteOperation);

            remoteMainOperation = new Intent.OperationBuilder()
                    .withDeviceId(DeviceUtils.getRemoteDevice().get(0).getDeviceId())
                    .withBundleName("com.example.daxiguaforharmony")
                    .withAbilityName("com.example.daxiguaforharmony.MainAbility")
                    .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                    .build();

            remoteMainIntent = new Intent();
            remoteMainIntent.setOperation(remoteMainOperation);
        }
    }

    /**
     * 查找鸿蒙设备
     */
    public void findDevice()
    {
        System.out.println("进入findDevice===");
        DeviceSelectDialog dialog = new DeviceSelectDialog(this.abilitySlice.getContext());
        dialog.setListener(deviceInfo -> {
            LogUtil.info(TAG, "continue button click===");
            LogUtil.debug(TAG, ": device name === " + deviceInfo.getDeviceName().toString());
            System.out.println(TAG + ": device name === " + deviceInfo.getDeviceName().toString());

            try {
                // 开始任务迁移
                //continueAbility();
                this.abilitySlice.continueAbility(deviceInfo.getDeviceId());
                LogUtil.info(TAG, "continue button click end===");
            } catch (IllegalStateException | UnsupportedOperationException e) {
                //WidgetHelper.showTips(this, ResourceTable.String_tips_mail_continue_failed);
                LogUtil.info(TAG, "continue button click error==="+e.getMessage());
            }
            dialog.hide();
        });
        dialog.show();
    }

    public void connectRemoteServices() {
        boolean success = false;
        if(localPlayerInterfaceProxy == null) {
            if(!this.abilitySlice.connectAbility(localIntent,localAbilityConnection)) {
                System.out.println("Game连接本地失败！==========");
            }else{
                System.out.println("Game连接本地成功！==========");
            }
        }
        if(!DeviceUtils.getRemoteDevice().isEmpty()) {
            if(remotePlayerInterfaceProxy == null) {
                try {
                    success = this.abilitySlice.connectAbility(remoteIntent, remoteAbilityConnection);
                    System.out.println("Game连接远程！==========" + success);
                } catch (Exception e) {
                    System.out.println("Game====" + e.getMessage());
                    e.printStackTrace();
                    //success = false;
                }
            }
        }
        //return true;
    }




    // ======================== IAbilityContinuation ==================================


    @Override
    public boolean onStartContinuation() {
        return true;
    }

    @Override
    public boolean onSaveData(IntentParams intentParams) {
        String exampleData = String.valueOf(System.currentTimeMillis());
        intentParams.setParam("continueParam", exampleData);
        return true;
    }

    @Override
    public boolean onRestoreData(IntentParams intentParams) {
        // 远端FA迁移传来的状态数据，开发者可以按照特定的场景对这些数据进行处理
        Object data = intentParams.getParam("continueParam");
        return true;
    }

    @Override
    public void onCompleteContinuation(int i) {
        CrossDeviceManager.getInstance().connectRemoteServices();
    }
}
